#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
Simplified BSD License (BSD)
THN HTTP Stack Library
Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 25-Apr-14 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;

using Thn;
using Thn.Net.Http;
#endregion

namespace Demo
{
    /// <summary>
    /// 
    /// </summary>
#if DEBUG 
    public
#else
    public
#endif 
    partial class fmMain : Form
    {
        #region Fields
        SimpleHttpServer mServer;
        #endregion

        #region Properties
        #endregion

        #region UI Events processing

        #region btnStart_Click
        private void btnStart_Click(object sender, EventArgs e)
        {
            StartServer();
        }
        #endregion

        #region btnStop_Click
        private void btnStop_Click(object sender, EventArgs e)
        {
            StopServer();
        }
        #endregion

        #endregion

        #region Server Events processing

        #region mServer_Started
        void mServer_Started(object sender, EventArgs e)
        {
            mIsStarting = false;
            UpdateUIBasedOnStatus();
        }
        #endregion

        #region mServer_StartFailed
        void mServer_StartFailed(object sender, Exception error)
        {
            mIsStarting = false;
            UpdateUIBasedOnStatus();

            this.RunOnUI((a) =>
            {
                Log.Warning("Could not start server");
                Log.Error(error);
            });
        }
        #endregion

        #region mServer_Stopped
        void mServer_Stopped(object sender, Exception error)
        {
            UpdateUIBasedOnStatus();
        }
        #endregion

        #endregion

        #region Update UI based on status
        bool mIsStarting = false;

        void UpdateUIBasedOnStatus()
        {
            this.RunOnUI((a) =>
            {
                if (mIsStarting)
                {
                    #region Server is starting
                    btnStart.Enabled = false;
                    btnStop.Enabled = false;
                    lblStatus.Text = "Starting...";
                    lblStatus.ForeColor = Color.Yellow;
                    #endregion
                }
                else if (mServer != null && mServer.IsListening)
                {
                    #region Server has started
                    btnStart.Enabled = false;
                    btnStop.Enabled = true;
                    lblStatus.Text = "Running...";
                    lblStatus.ForeColor = Color.GreenYellow;
                    #endregion
                }
                else
                {
                    #region Server has stopped
                    btnStart.Enabled = true;
                    btnStop.Enabled = false;
                    lblStatus.Text = "Stopped";
                    lblStatus.ForeColor = Color.Red;
                    #endregion
                }
            });
        }
        #endregion

        #region Intialize Server
        void InitializeServer()
        {
            if (mServer == null)
            {
                mServer = new SimpleHttpServer();
                mServer.Stopped += mServer_Stopped;
                mServer.StartFailed += mServer_StartFailed;
                mServer.Started += mServer_Started;

                //register my own HTTP request handler
                mServer.RequestHandlers.Add(new MyRequestHandler());
            }
            #region Defensive tracing
            else
            {
                //already initialized
            }
            #endregion
        }
        #endregion

        #region Start Server
        void StartServer()
        {
            InitializeServer();

            if (!mServer.IsListening)
            {
                mServer.Port = txtPort.Text.Parse<int>();
                mIsStarting = true;
                UpdateUIBasedOnStatus();
                mServer.Start();
            }
            #region Defensive tracing
            else
            {
                //already started
            }
            #endregion
        }
        #endregion

        #region Stop Server
        void StopServer()
        {
            if (mServer != null && mServer.IsListening)
            {
                mServer.Stop();
            }
            #region Defensive tracing
            else
            {
                //not running, no need to stop
            }
            #endregion
        }
        #endregion

        #region Form Closing
        private void fmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //always remember to stop the server to release the sockets used
            StopServer();
        }
        #endregion
        
        #region On Load
        /// <summary>
        /// Initialize this form when form is loaded.
        /// </summary>
        protected override void OnLoad(EventArgs e)
        {
            if (!DesignMode)
            {
#if DEBUG
                //setup logging
                Log.Logger.SetPriorityFilter(LogPriority.Debug);
#endif
                UpdateUIBasedOnStatus();

#if DEBUG
                //auto-start
                StartServer();
#endif
            }
            #region Defensive tracing
            else
            {
                //don't do anything at design-time
            }
            #endregion

            //let my ancestor process its own logic
            base.OnLoad(e);
        }
        #endregion
        
        #region Constructors
        /// <summary>
        /// Default constructor.
        /// </summary>
        public fmMain() 
        {
            InitializeComponent();
        }
        #endregion
    }
}
